package dd.server;

import javax.management.modelmbean.ModelMBeanAttributeInfo;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

import server.ClientState;
import server.IProtocolHandler;
import server.Server;
import xml.Message;
import dd.model.Event;
import dd.model.serverModel;

public class addChoiceResponseController implements IProtocolHandler {
	public Message process(ClientState client, Message request) {
		serverModel sm = serverModel.getInstance();
		Event e = sm.getEvent();
		Node update = request.contents.getFirstChild();
		NamedNodeMap map = update.getAttributes();
		//get information
		String geteventid = map.getNamedItem("id").getNodeValue();
		String numberr = map.getNamedItem("number").getNodeValue();
		int number = Integer.parseInt(numberr);
		String choice = map.getNamedItem("choice").getNodeValue();
		System.out.println("receivedid: choice "+numberr+": " + choice);
		e.setChoice(number, choice);
		// Construct message reflecting state
		String xmlString = Message.responseHeader(request.id()) +
				 "<addChoiceResponse id='"+geteventid+"' number='"+numberr+"' choice='"
				+choice+"'>"+"</addChoiceResponse></response>";
		Message m =new Message(xmlString);
		//send this response to all the client
		for(String id :Server.ids()){
			if (!id.equals(client.id())) {
				Server.getState(id).sendMessage(m);
			}
		}
		// send this response back to the client which sent us the request.
		return m;
	}
}
